<template>
  <a-modal
      v-model:visible="visible"
      title="合集详细信息"
      :width="800"
      @cancel="handleCancel"
  >
    <!-- 加载状态 -->
    <div v-if="isLoading" class="loading-container">
      <a-spin size="large" tip="加载详情中..." />
    </div>

    <!-- 错误状态 -->
    <div v-else-if="hasError" class="error-container">
      <a-empty description="获取合集详情失败，请重试" />
      <a-button type="primary" style="margin-top: 16px" @click="fetchCollectionDetail">
        重新加载
      </a-button>
    </div>

    <!-- 详情内容 -->
    <div class="collection-detail" v-else-if="collectionDetail">
      <!-- 封面展示 -->
      <div class="cover-container">
        <img :src="getCoverUrl(collectionDetail.coverUrl)" alt="合集封面" class="cover-img" />
      </div>

      <!-- 基本信息 -->
      <div class="info-container">
        <h3 class="collection-name">{{ collectionDetail.name }}</h3>
        <p class="collection-desc">{{ collectionDetail.description }}</p>
        <div class="meta-info">
          <span>
            <CalendarOutlined /> 创建时间：{{ formatDate(collectionDetail.createTime) }}
          </span>
          <span>
            <ClockCircleOutlined /> 更新时间：{{ formatDate(collectionDetail.updateTime) }}
          </span>
          <span>
            状态：{{ getStatusText(collectionDetail.status) }}
          </span>
        </div>

        <!-- 作品列表 -->
        <div class="works-section" v-if="worksList.length > 0">
          <h4>合集中作品 ({{ worksList.length }})</h4>
          <div class="works-list">
            <div
                class="work-item"
                v-for="(work, index) in worksList"
                :key="work.id"
                @click.stop="openWorkDetail(work.id)"
            >
              <img :src="getWorkCover(work)" alt="作品封面" class="work-cover" />
              <span class="debug-id">{{ work.id }}</span>
              <span class="work-name">{{ work.worksName }}</span>
            </div>
          </div>
        </div>

        <!-- 作品空状态 -->
        <div v-else class="no-works">
          <a-empty description="该合集中暂无作品" />
        </div>
      </div>
    </div>
  </a-modal>

  <!-- 作品详情弹窗 -->
  <WorkDetailModal
      v-model:visible="workDetailVisible"
      :work-id="selectedWorkId"
      :minio-url="minioUrl"
      :work-tag-map="workTagMap"
  />
</template>

<script setup lang="ts">
import {ref, watch, defineProps, defineEmits, nextTick} from 'vue';
import { CalendarOutlined, ClockCircleOutlined } from '@ant-design/icons-vue';
import { getCollectionWorksDetail } from '@/api/media/bizCollectionController';
import WorkDetailModal from "@/components/profile/WorkDetailModal.vue";

// 定义类型
interface BizCollection {
  id: number;
  userId: number;
  name: string;
  coverUrl: string;
  description: string;
  status: number;
  createTime: string;
  updateTime: string;
}

interface BizWorks {
  id: number;
  worksName: string;
  coverFileUrl: string;
  duration: string;
  createTime: string;
  isCharge: number;
  status: number;
}

interface CollectionWorksDetailVo extends BizCollection {
  bizWorksList: BizWorks[];
}

const workDetailVisible = ref(false);
const selectedWorkId = ref<number | null>(null);
const minioUrl = import.meta.env.VITE_MINIO_URL;
const workTagMap = ref<Record<number, string[]>>({});

// 接收父组件参数
const props = defineProps<{
  collectionId: number;
  visible: boolean;
}>();

// 向父组件传递事件
const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void;
}>();

// 组件内部状态
const visible = ref(props.visible);
const collectionDetail = ref<CollectionWorksDetailVo | null>(null);
const worksList = ref<BizWorks[]>([]);
const isLoading = ref(false);
const hasError = ref(false);

// 打开作品详情弹窗
const openWorkDetail = (workId: number) => {
  console.log('🎯 点击了作品项，workId:', workId);

  selectedWorkId.value = workId;
  workDetailVisible.value = true;

  console.log('✅ selectedWorkId:', selectedWorkId.value);
  console.log('✅ workDetailVisible:', workDetailVisible.value);
};

// 添加点击测试函数
const testClick = (workId: number, event: MouseEvent) => {
  console.log('🧪 测试点击 - workId:', workId);
  console.log('🧪 事件目标:', event.target);
  console.log('🧪 当前目标:', event.currentTarget);
  event.stopPropagation();
  openWorkDetail(workId);
};

// 同步visible状态
watch(
    () => props.visible,
    (newVisible) => {
      visible.value = newVisible;
      console.log('📱 visible状态变化:', newVisible);
    }
);

// 监听内部visible状态变化
watch(
    () => visible.value,
    (newVisible) => {
      emit('update:visible', newVisible);
      console.log('🔄 内部visible变化:', newVisible);

      if (newVisible && props.collectionId) {
        console.log('📥 打开弹窗，开始获取数据，ID:', props.collectionId);
        fetchCollectionDetail();
      } else {
        console.log('📤 关闭弹窗，重置数据');
        collectionDetail.value = null;
        worksList.value = [];
        hasError.value = false;
        selectedWorkId.value = null;
        workDetailVisible.value = false;
      }
    }
);

// 监听collectionId变化
watch(
    () => props.collectionId,
    (newId) => {
      console.log('🆔 collectionId变化:', newId);
      if (newId && visible.value) {
        fetchCollectionDetail();
      }
    }
);

// 获取详情数据
const fetchCollectionDetail = async () => {
  if (!props.collectionId) {
    console.error('❌ collectionId为空');
    return;
  }

  isLoading.value = true;
  hasError.value = false;

  try {
    console.log('🌐 开始请求合集详情，ID:', props.collectionId);
    const response = await getCollectionWorksDetail({
      collectionId: props.collectionId
    });

    console.log('📦 API响应:', response);

    if (response.code === '00000' && response.data) {
      collectionDetail.value = response.data;
      worksList.value = response.data.bizWorksList || [];
      console.log('✅ 成功获取数据，作品数量:', worksList.value.length);

      // 数据加载后，确保DOM更新完成
      nextTick(() => {
        console.log('🎨 DOM更新完成，可以绑定事件');
        addClickListeners();
      });
    } else {
      console.error('❌ 获取合集详情失败', response.message);
      hasError.value = true;
    }
  } catch (error) {
    console.error('❌ 请求接口出错', error);
    hasError.value = true;
  } finally {
    isLoading.value = false;
  }
};

// 手动添加点击监听器（备用方案）
const addClickListeners = () => {
  const workItems = document.querySelectorAll('.work-item');
  console.log('🔍 找到作品项:', workItems.length);

  workItems.forEach((item, index) => {
    const workId = worksList.value[index]?.id;
    if (workId) {
      item.addEventListener('click', (event) => {
        console.log('🖱️ 手动监听器触发，workId:', workId);
        event.stopPropagation();
        openWorkDetail(workId);
      });
    }
  });
};

// 关闭弹窗
const handleCancel = () => {
  console.log('❌ 用户点击关闭');
  visible.value = false;
};

// 工具函数保持不变...
function getCoverUrl(coverUrl?: string) {
  if (!coverUrl) return '';
  const minioUrl = import.meta.env.VITE_MINIO_URL;
  return minioUrl + coverUrl;
}

function getWorkCover(work: BizWorks) {
  if (!work.coverFileUrl) return '';
  const minioUrl = import.meta.env.VITE_MINIO_URL;

  if (work.coverFileUrl.startsWith('http')) {
    return work.coverFileUrl;
  }

  const cleanCoverPath = work.coverFileUrl.replace(/^\//, '');
  const baseUrl = minioUrl.endsWith('/') ? minioUrl : `${minioUrl}/`;
  return `${baseUrl}${cleanCoverPath}`;
}

function formatDate(dateString: string) {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString();
}

function getStatusText(status: number) {
  const statusMap: Record<number, string> = {
    1: '开放',
    2: '隐藏'
  };
  return statusMap[status] || '未知';
}
</script>

<style scoped>
.collection-detail {
  display: flex;
  flex-direction: row;
  gap: 20px;
  padding: 10px 0;
}

.cover-container {
  width: 200px;
  flex-shrink: 0;
}

.cover-img {
  width: 100%;
  height: auto;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.info-container {
  flex: 1;
  min-width: 0;
}

.collection-name {
  font-size: 20px;
  font-weight: 600;
  margin: 0 0 12px 0;
  color: #141414;
}

.collection-desc {
  color: #666;
  margin: 0 0 16px 0;
  line-height: 1.6;
  white-space: pre-line;
}

.meta-info {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 24px;
  color: #888;
  font-size: 14px;
}

.meta-info span {
  display: flex;
  align-items: center;
  gap: 4px;
}

.works-section {
  margin-top: 24px;
}

.works-section h4 {
  font-size: 16px;
  margin: 0 0 12px 0;
  color: #141414;
}

.works-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-top: 12px;
}

.work-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 120px;
  cursor: pointer;
  position: relative;
  padding: 8px;
  border: 2px solid transparent;
  border-radius: 8px;
  transition: all 0.2s ease;
}

.work-item:hover {
  border-color: #1890ff;
  background-color: #f0f8ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.2);
}

.work-item:active {
  transform: translateY(0);
  border-color: #096dd9;
}

.work-cover {
  width: 100%;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
  margin-bottom: 8px;
  pointer-events: none; /* 防止图片阻止点击事件 */
}

.work-name {
  text-align: center;
  font-size: 12px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
  pointer-events: none; /* 防止文字阻止点击事件 */
}

.debug-info {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 0, 0, 0.1);
  color: red;
  font-size: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.2s;
}

.work-item:hover .debug-info {
  opacity: 1;
}

.loading-container, .error-container, .no-works {
  width: 100%;
  padding: 60px 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .collection-detail {
    flex-direction: column;
  }

  .cover-container {
    width: 100%;
    margin-bottom: 16px;
  }

  .meta-info {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }

  .work-item {
    width: 100px;
  }
}
</style>